<template>
  <div class="container">
    <el-card style="position: relative">
      <RouterHeader :title="title()"></RouterHeader>
      <el-form
        :model="form"
        :rules="rules"
        ref="ruleFormRef"
        label-width="140px"
        label-position="right"
      >
        <el-row :gutter="20" class="form-single-info">
          <el-col :span="20">
            <el-row>
              <el-col :span="8">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input
                    class="input-item"
                    v-model="form.projectName"
                    placeholder="请输入"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="项目编码" prop="projectEncode">
                  <el-input
                    class="input-item"
                    v-model="form.projectEncode"
                    placeholder="请输入"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="业务类型" prop="businessTypeList">
                  <el-cascader
                    v-model="form.businessTypeList"
                    ref="ref_business"
                    :options="businesstypeTree"
                    :props="businesstProps"
                    :show-all-levels="false"
                    clearable
                    disabled
                  ></el-cascader>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="复盘发起人" prop="reviewPerson">
                  <el-select
                    v-model="form.reviewPerson"
                    clearable
                    placeholder="请选择"
                    filterable
                    :disabled="isDisabled()"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.nickName"
                      :label="item.nickName"
                      :value="item.nickName"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="复盘参与人" prop="reviewParticipants">
                  <el-select
                    v-model="form.reviewParticipantsList"
                    multiple
                    clearable
                    filterable
                    placeholder="请选择"
                    :disabled="isDisabled()"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.nickName"
                      :label="item.nickName"
                      :value="item.userId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="复盘时间" prop="reviewTime">
                  <el-date-picker
                    v-model="form.reviewTime"
                    type="datetime"
                    placeholder="选择日期"
                    style="width: 100%"
                    :disabled="isDisabled()"
                    format="YYYY-MM-DD HH:mm:ss"
                    value-format="YYYY-MM-DD HH:mm:ss"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目执行情况" prop="projectImplementation">
                  <el-input
                    class="input-item"
                    type="textarea"
                    :autosize="{ minRows: 2 }"
                    show-word-limit
                    v-model="form.projectImplementation"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item
                  label="项目出现的问题及原因及解决方法"
                  prop="questionSettle"
                >
                  <el-input
                    class="input-item"
                    type="textarea"
                    :autosize="{ minRows: 2 }"
                    show-word-limit
                    v-model="form.questionSettle"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="项目可借鉴之处" prop="projectReference">
                  <el-input
                    class="input-item"
                    type="textarea"
                    :autosize="{ minRows: 2 }"
                    show-word-limit
                    v-model="form.projectReference"
                    placeholder="请输入"
                    :disabled="isDisabled()"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="客户反馈表" prop="customerFileList">
                  <fileupload v-if="ist == '3'"
                    @update:modelValue="customerFeedback"
                    :modelValue="form.customerFileList"
                    :flag="route.query.name === '6' ? true : false"
                  ></fileupload>
                  <indexcategory v-if="ist == '1'" 
                    @update:modelValue="customerFeedback"
                    :modelValue="form.customerFileList"
                    :flag="route.query.name === '6' ? true : false">
                  </indexcategory>
                  <indexcategorysecond v-if="ist == '2'" 
                    @update:modelValue="customerFeedback"
                    :modelValue="form.customerFileList"
                    :flag="route.query.name === '6' ? true : false">
                  </indexcategorysecond>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="其他附件/图片" prop="otherFileList">
                  <fileupload v-if="ist == '3'" 
                    @update:modelValue="otherAttachment"
                    :modelValue="form.otherFileList"
                    :flag="route.query.name === '6' ? true : false"
                  ></fileupload>
                  <indexcategory v-if="ist == '1'" 
                    @update:modelValue="otherAttachment"
                    :modelValue="form.otherFileList"
                    :flag="route.query.name === '6' ? true : false">
                  </indexcategory>
                  <indexcategorysecond v-if="ist == '2'" 
                    @update:modelValue="otherAttachment"
                    :modelValue="form.otherFileList"
                    :flag="route.query.name === '6' ? true : false">
                  </indexcategorysecond>
                </el-form-item>
              </el-col>
            </el-row>
            <div class="title" v-if="route.query.name !== '1'">
              <h5>意见栏</h5>
            </div>
            <div class="yijian" v-if="route.query.name !== '1'">
              <el-input
                class="input-yijian"
                type="textarea"
                :autosize="{ minRows: 2 }"
                show-word-limit
                v-model="form.opinion"
                placeholder="请输入内容"
              ></el-input>
            </div>
            <div class="fabu" v-if="route.query.name !== '1'">
              <el-button type="primary" size="mini" @click="publish"
                >发布</el-button
              >
            </div>
            <div
              class="text-content"
              v-if="route.query.name !== '1' && opinionList.length > 0"
            >
              <div
                class="custom-concent"
                v-for="item in opinionList"
                :key="item"
              >
                <div class="custom-wrapper">
                  <img :src="url + item.profilePicture" class="custom-avatar" />
                </div>
                <div class="custom-text">
                  <div class="text-top">
                    <div
                      style="
                        font-size: 16px;
                        font-weight: bold;
                        color: #ff8200;
                        white-space: nowrap;
                      "
                    >
                      {{ item.userName }}({{ item.deptName }})：
                    </div>
                    <div class="text-time">{{ item.releaseTime }}</div>
                  </div>
                  <div class="text-bottom">
                    <div class="custom-reply">{{ item.opinionContent }}</div>
                  </div>
                </div>
              </div>
            </div>

            <!-- <div v-if="route.query.name !== '1'">
              <div class="title"><h5>项目审批进度</h5></div>
              <el-timeline style="max-width: 600px">
                <el-timeline-item
                  v-for="(item, index) in activities"
                  :key="index"
                  :timestamp="item.createTime"
                >
                  <div style="display: flex; align-items: center">
                    <img :src="url + item.avatar" class="user-avatar" />
                    <span style="font-size: 12px; margin-left: 5px">
                      {{ item.username }}:</span
                    >
                    <span
                      style="
                        font-size: 14px;
                        font-weight: 400;
                        margin-left: 5px;
                      "
                    >
                      {{ item.opinion }}</span
                    >
                  </div>
                </el-timeline-item>
              </el-timeline>
            </div> -->
            <!-- <el-col v-if="route.query.name !== '3'">
              <div class="title"><h5>项目审批流程</h5></div>
              <el-row>
                <el-col :span="24" v-if="form.keepCheck === '1'">
                  <el-form-item label="审批流程" style="padding: 20px 0">
                    <approver
                      :approverList="form.processCheckBo.checkPeopleIds"
                      :isEdit="!!$route.query.id"
                      @handleChooseapprover="handleChooseapprover"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="24" v-if="form.keepCheck === '1'">
                  <el-form-item label="抄送" style="padding: 20px 0">
                    <approver
                      :approverList="form.processCheckBo.copyFor"
                      :isCc="true"
                      @handleChooseapprover="handleChooseapproverCc"
                    ></approver>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-col> -->
            <el-row v-if="route.query.name === '6' || route.query.name === '5'">
              <el-col :span="24">
                <el-form-item label="审批意见" prop="projectImplementation">
                  <el-input
                    class="input-item"
                    type="textarea"
                    :autosize="{ minRows: 2 }"
                    show-word-limit
                    v-model="form.approvalOpinions"
                    placeholder="请输入"
                    :disabled="route.query.name === '5' ? true : false"
                  ></el-input>
                </el-form-item>
                <el-form-item label="添加附件" prop="approvalFiles">
                  <fileupload
                    @update:modelValue="approvalFilesAdd"
                    :modelValue="form.approvalFiles"
                  ></fileupload>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item
                  label="审批决定"
                  :disabled="route.query.nmae === '5' ? true : false"
                >
                  <el-radio-group
                    v-model="form.keepCheck"
                    class="ml-4"
                    :disabled="route.query.name === '5' ? true : false"
                  >
                    <el-radio label="0" size="large">完成审批</el-radio>
                    <el-radio label="1" size="large">继续审批</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>

        <div
          style="display: flex; justify-content: center; margin-top: 20px"
          v-if=" route.query.name !== '3'"
        >
          <el-button @click="resetForm">{{
            route.query.name === "6" ? "驳回" : "取消"
          }}</el-button>
          <el-button type="primary" @click="submitForm">{{
            route.query.name === "6" ? "通过" : "提交"
          }}</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>
<script setup>
import RouterHeader from "@/components/RouterHeader";
import { ref, reactive, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import fileupload from "@/components/FileUpload/index";
import indexcategory from "@/components/FileUpload/indexcategory";
import indexcategorysecond from "@/components/FileUpload/indexcategorysecond";
import {
  reviewInfo,
  reviewPerson,
  reviewSubmit,
  addReview,
  opinionRelease,
  opinionInquiry,
} from "@/api/project/review";
import { businessTypeList,getbusinessTypeDic } from "@/api/project/conversion";
import approver from "@/components/Approve/approver";
import { ElMessage } from "element-plus";
import { approvalQuery } from "@/api/project/approval";
import {
  approvalProcessApi,
  replayApprove,
} from "@/api/approvalManagement/approvaType.js";
import useUserStore from "@/store/modules/user";
const userStore = useUserStore();
let url = import.meta.env.VITE_APP_BASE_API;
const activities = ref([]);
const radio1 = ref("2");
const title = () => {
  if (route.query.name === "1") {
    return "新增复盘";
  } else if (route.query.name === "2") {
    return "编辑复盘";
  } else {
    return "复盘详情";
  }
};
const route = useRoute();
const router = useRouter();
const form = reactive({
  projectName: "", // 项目名称
  projectEncode: "", //  项目编码
  businessTypeList: "", // 业务类型
  reviewPerson: "", // 项目发起人
  reviewParticipantsList: "", //复盘参与人

  reviewTime: "", // 复盘时间
  projectImplementation: "", // 项目执行情况
  questionSettle: "", // 项目出现的问题及原因及解决方法
  projectReference: "", // 项目可借鉴之处
  customerFileList: [], // 客户反馈文件
  otherFileList: [], // 其他文件
  processCheckBo: {
    checkPeopleIds: [], //审核人id列表
    copyFor: [], //抄送人id列表
  },
  reviewId: Number(route.query.id),
  approvalOpinions: "", // 审批意见
  processCheckHistoryId: "",
  approvalFiles: [],
  keepCheck: "1", //审批决定-继续审批
  opinion: "",
});
// 复盘发起人查询
const options = ref([]);
const reviewPersonQuery = async () => {
  const res = await reviewPerson(form.reviewPerson);
  console.log(res);
  if (res.code === 200) {
    options.value = res.rows;
  }
};
// 业务类型树形列表
const businesstypeTree = ref([]);
// 获取业务类型树形列表
const businessTypeOptions = async () => {
  const response = await businessTypeList();
  if (response.code === 200 && response.data.length > 0) {
    businesstypeTree.value = response.data;
    // console.log(businesstypeTree.value);
  }
};
// 业务类型props配置
const businesstProps = {
  value: "id",
  label: "businessName",
  children: "children",
  // checkStrictly: true,
  multiple: true,
};
let memberId = ref();
// 归档页面点击复盘回显
const reviewAdd = async () => {
  let params = {
    id: Number(route.query.archivistId),
  };
  const res = await approvalQuery(params);
  
  if (res.code === 200 && res.data) {
    form.projectName = res.data.projectName;
    form.projectEncode = res.data.proId;

    //通过判断业务类型的，来显示上传文件框
    form.businessTypeList = res.data.test;
    ist.value = showFileUpload(res.data.test);

    memberId.value = res.data.memberId;
  }
};
// 查看详情
const reviewDetails = async () => {
  let params = Number(route.query.id);
  const res = await reviewInfo(params);
  console.log(res);
  if (res.code === 200 && res.data) {
    for (let key in form) {
      if (res.data[key]) {
        form[key] = res.data[key];
      }
    }

    //通过判断业务类型的，来显示上传文件框
    form.businessTypeList = res.data.test;
    ist.value = showFileUpload(res.data.test);

    // form.processCheckHistoryId = res.data.dataCheckInfo?.processCheckHistoryId;
    // activities.value = res.data.dataCheckInfo?.opinons;
    // form.reviewParticipants=res
    form.reviewParticipantsList =
      res.data.reviewParticipants && JSON.parse(res.data.reviewParticipants);
    if (route.query.name === "5") {
      form.approvalOpinions =
        res.data &&
        res.data.dataCheckInfo &&
        res.data.dataCheckInfo.myCheckOpinionBo &&
        res.data.dataCheckInfo.myCheckOpinionBo.opinion;
      form.approvalFiles =
        res.data &&
        res.data.dataCheckInfo &&
        res.data.dataCheckInfo.myCheckOpinionBo &&
        res.data.dataCheckInfo.myCheckOpinionBo.fileList;
      form.keepCheck =
        res.data &&
        res.data.dataCheckInfo &&
        res.data.dataCheckInfo.myCheckOpinionBo &&
        res.data.dataCheckInfo.myCheckOpinionBo.keepCheck;
    }
  }
};

//控制上传组件的显示
const ist = ref('3');
const showFileUpload=(e)=>{
  //类型1为'a-j',类型2为'册'
  //返回值示例：
  // [
  //   {
  //       "type": "6,89",
  //       "value": 1
  //   },
  //   {
  //       "type": "[6,88],[6,90]",
  //       "value": 2
  //   }
  // ]

  //先判断类型1，再判断类型2，其它为3
  let typedic1 = businessTypeDicData.filter(o=>{ if(o.value == 1) return o } );
  let typedic2 = businessTypeDicData.filter(o=>{ if(o.value == 2) return o } );
  let result = '3';
  //进行业务类型的判断
  if(e.length == 0){
    return result;
  }
  e.forEach(function(item){
    typedic1.filter(function(o){
      let typearr = JSON.parse("["+ o.type +"]");
      typearr.forEach(function(p){
        if(p.length == 2 
        && p.length == item.length 
        && p[0] == item[0]
        && p[1] == item[1]){
          result = typedic1[0].value;
        }
        else if(p.length == 1 
        && p.length == item.length 
        && p[0] == item[0]){
          result = typedic1[0].value;
        }
      });
    });
  });

  if(result == '1'){
    return result;
  }
  e.forEach(function(item){
    typedic2.filter(function(o){
      let typearr = JSON.parse("["+ o.type +"]");
      typearr.forEach(function(p){
        if(p.length == 2 
        && p.length == item.length 
        && p[0] == item[0]
        && p[1] == item[1]){
          result = typedic2[0].value;
        }
        else if(p.length == 1 
        && p.length == item.length 
        && p[0] == item[0]){
          result = typedic2[0].value;
        }
      });
    });
  });

  return result;
}

// 控制表单是否只读
const disabled = ref(true);
const isDisabled = () => {
  if (
    route.query.name === "3" ||
    route.query.name === "6" ||
    route.query.name === "5"
  ) {
    return (disabled.value = true);
  } else {
    return (disabled.value = false);
  }
};
// 审批人
const handleChooseapprover = (id) => {
  if (id) {
    form.processCheckBo.checkPeopleIds = id;
  }
};
// 抄送人
const handleChooseapproverCc = (id) => {
  if (id) {
    form.processCheckBo.copyFor = id;
  }
};

// 意见栏发布
const publish = async () => {
  let data = {
    reviewId: Number(route.query.id),
    opinionContent: form.opinion,
  };
  const res = await opinionRelease(data);
  opinionQuery();
  form.opinion = "";
};

const opinionList = ref([]);
// 意见查询
const opinionQuery = async () => {
  let params = {
    opinionContent: form.opinion,
    reviewId: Number(route.query.id),
  };
  const res = await opinionInquiry(params);
  if (res.code === 200 && res.rows) {
    opinionList.value = res.rows;
  }
};
// 客户反馈表
const customerFeedback = (val, result, operationType) => {
  if (operationType === "success") {
    if (result) {
      form.customerFileList = [];
      result.forEach((item)=>{
        form.customerFileList.push(item);
      });
    }
  } else if (operationType === "delete") {
    form.customerFileList.splice(result, 1);
  }
};
// 其他附件
const otherAttachment = (val, result, operationType) => {
  if (operationType === "success") {
    if (result) {
      form.otherFileList = [];
      result.forEach((item)=>{
        form.otherFileList.push(item);
      });
    }
  } else if (operationType === "delete") {
    form.otherFileList.splice(result, 1);
  }
};
// 审批附件
const approvalFilesAdd = (val, result, operationType) => {
  if (operationType === "success") {
    if (result) {
      form.approvalFiles = [];
      result.forEach((item)=>{
        form.approvalFiles.push(item);
      });
    }
  } else if (operationType === "delete") {
    form.approvalFiles.splice(result, 1);
  }
};
// 状态
const getUserStatusType = (status) => {};
// 取消/驳回
const resetForm = async () => {
  if (route.query.name === "6") {
    let data = {
      checkOpinion: form.approvalOpinions,
      id: form.processCheckHistoryId,
      copyFor: form.processCheckBo.copyFor.map((item) => item.userId),
      keepCheckId: form.processCheckBo.checkPeopleIds.map(
        (item) => item.userId
      ),
      state: "0",
      fileList: form.approvalFiles,
      keepCheck: form.keepCheck,
    };
    const res = await replayApprove(data);
    if (res.code === 200) {
      ElMessage.success("审批已驳回");
      router.go(-1);
    }
  } else {
    router.go(-1);
  }
};
// 提交/通过
const submitForm = async () => {
  // 新增
  if (route.query.name === "1") {
    // 编辑
    let userCcIds;
    let userIds;
    if (form.processCheckBo.checkPeopleIds) {
      userIds = form.processCheckBo.checkPeopleIds.map((item) =>
        item.userId ? Number(item?.userId) : item
      );
    }
    if (form.processCheckBo.copyFor) {
      userCcIds = form.processCheckBo.copyFor.map((item) =>
        item.userId ? Number(item?.userId) : item
      );
    }
    const res = await addReview({
      ...form,
      archivistId: Number(route.query.id),
      memberId: memberId.value,
      reviewParticipants: "",
      processCheckBo: {
        checkPeopleIds: userIds,
        copyFor: userCcIds,
      },
    });
    if (res.code === 200) {
      ElMessage.success("添加成功");
      router.push({ path: "/project/review" });
    }
  } else if (route.query.name === "2") {
    // 编辑
    let userCcIds;
    let userIds;
    if (form.processCheckBo.checkPeopleIds) {
      userIds = form.processCheckBo.checkPeopleIds.map((item) =>
        Number(item?.userId)
      );
    }
    if (form.processCheckBo.copyFor) {
      userCcIds = form.processCheckBo.copyFor.map((item) =>
        Number(item?.userId)
      );
    }
    const res = await reviewSubmit({
      ...form,
      reviewParticipants: "",
      processCheckBo: {
        checkPeopleIds: userIds,
        copyFor: userCcIds,
      },
    });
    if (res.code === 200) {
      ElMessage.success("保存成功");
      router.push({ path: "/project/review" });
    }
  } else {
    let data = {
      checkOpinion: form.approvalOpinions,
      id: form.processCheckHistoryId,
      copyFor: form.processCheckBo.copyFor.map((item) => item.userId),
      keepCheckId: form.processCheckBo.checkPeopleIds.map(
        (item) => item.userId
      ),
      state: "1",
      fileList: form.approvalFiles,
      keepCheck: form.keepCheck,
    };
    const res = await replayApprove(data);
    if (res.code === 200) {
      ElMessage.success("审批通过");
      router.push({
        path: "/examine",
      });
    }
  }
};


let businessTypeDicData = [];
//获取
const getbusinessTypeDicData = async() => {
  //类型1为'a-j',类型2为'册'
  //返回值示例：
  // [
  //   {
  //       "type": "6,89",
  //       "value": 1
  //   },
  //   {
  //       "type": "[6,88],[6,90]",
  //       "value": 2
  //   }
  // ]
  let response = await getbusinessTypeDic();
  if (response.code === 200 && response.rows.length > 0) {
    businessTypeDicData = response.rows;
  } else {
    console.log(err);
  }

}


onMounted(async () => {
  // (await route.query.name) === "1" ? reviewAdd() : reviewDetails();
  await getbusinessTypeDicData();
  if (route.query.name === "1") {
    await reviewAdd();
  } else {
    await reviewDetails();
  }
  await businessTypeOptions();
  await reviewPersonQuery();
  await opinionQuery();
});
</script>

<style scoped lang="scss">
.el-form {
  margin-top: 30px;
}
.el-dialog {
  background: #fff;
}
.custom-avatar {
  width: 50px;
  height: 50px;
  border-radius: 10px;
}
/**
   * form表单输入组件宽度
   **/

.el-select {
  width: 100%;
}

.el-input {
  width: 100%;
}

.el-cascader {
  width: 100%;
}

.el-date-editor {
  width: 100%;
}

.el-input-number {
  width: 100%;
}
</style>

<style lang="scss" scoped>
.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 10px;
}
.container {
  padding: 20px;
}
.form-single-info {
  display: flex;
  justify-content: center;
}
.el-form-info {
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.05);
  padding: 20px;
}
.el-form-info strong {
  margin: 0 10px;
}
.el-form-info .el-time-picker {
  width: 100%;
}
.title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  h5 {
    font-weight: bold;
  }
}
.yijian {
  margin-left: 70px;
}
.Approver {
  display: flex;
  .Approver_content {
    display: flex;
    align-items: center;
    .img_content {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin-left: 10px;
      .el-tag {
        margin-top: 10px;
      }
    }
  }
}
.query_input {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.fabu {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}
.text-content {
  height: 250px;
  margin-left: 70px;
  background: #f8f8f9;
  margin-top: 20px;
  overflow: auto;
  padding: 20px;
  .custom-concent {
    width: 100%;
    height: 70px;
    display: flex;
    margin-top: 8px;
    .custom-text {
      display: flex;
      width: 100%;
      margin-left: 10px;
      .text-top {
        display: flex;
        flex-direction: column;
        .text-time {
          color: #939393;
          font-size: 16px;
          margin-top: 10px;
        }
      }
      .text-bottom {
        display: flex;
        justify-content: space-between;
      }
    }
    .custom-avatar {
      width: 50px;
      height: 50px;
      border-radius: 10px;
    }
    .custom-reply {
      color: #333;
      font-size: 16px;
      margin-left: 10px;
      word-break: break-all;
    }
  }
}
</style>
